package com.glasgowcompsoc.musicplayer.ui;

import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.glasgowcompsoc.musicplayer.R;
import com.glasgowcompsoc.musicplayer.player.Song;

public class FetchAlbumArtTask extends AsyncTask<Song, Integer, Bitmap> {
	private Context context;
	private ImageView imageView;
	
	public FetchAlbumArtTask(Context context, ImageView imageView) {
		this.context = context;
		this.imageView = imageView;
	}
	
	/* Before the task starts, set the temporary album art drawable.*/
	@Override
	protected void onPreExecute() {
		imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.music));
	}
	
	/* This is the main part of the AsyncTask; all processing takes place here! This
	 * happens on a non-UI thread, so it doesn't cause the app to become unresponsive
	 * to input.
	 */
	@Override
	protected Bitmap doInBackground(Song... args) {
		Song nowPlaying = args[0];

		/*
		 * Normally we'd look for cover art properly; it may be embedded in the ID3 data, in the album folder, or we
		 * may search on last.fm or Amazon. To keep this example simple, we'll just load an image locally.
		 * 
		 * If we were downloading cover art online, we wouldn't want this to happen in the UI thread; the UI would
		 * become unresponsive while the image downloads. This lack of response is sometimes called "jank" in
		 * Android jargon.
		 */

		/* Assume that in this example, cover art filename is lowercase album name with spaces replaced by hyphens. */
		String album = nowPlaying.getAlbum();
		String covertArtFilename = album.toLowerCase().replace(' ', '-').concat(".jpg");

		InputStream coverArtStream;

		try {
			coverArtStream = context.getAssets().open(covertArtFilename);
		} catch (IOException e) {
			return null;
		}

		return BitmapFactory.decodeStream(coverArtStream);
	}

	/* onPreExecute and onPostExecute both get executed on the UI thread. Perfect
	 * for updating the UI with the result of a task. In this case, set the proper
	 * cover art image.
	 */
	@Override
	protected void onPostExecute(Bitmap coverArt) {
		if (coverArt == null) {
			return;
		}
		
		imageView.setImageBitmap(coverArt);
	}
}